package net.lab1024.sa.common.module.support.jdunion;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.util.concurrent.AtomicDouble;
import com.jd.open.api.sdk.JdClient;
import com.jd.open.api.sdk.domain.kplunion.CategoryService.request.get.CategoryReq;
import com.jd.open.api.sdk.domain.kplunion.GoodsService.request.query.JFGoodsReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.request.query.OrderRowReq;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.OrderRowQueryResult;
import com.jd.open.api.sdk.domain.kplunion.OrderService.response.query.OrderRowResp;
import com.jd.open.api.sdk.domain.kplunion.promotioncommon.PromotionService.request.get.PromotionCodeReq;
import com.jd.open.api.sdk.request.kplunion.UnionOpenCategoryGoodsGetRequest;
import com.jd.open.api.sdk.request.kplunion.UnionOpenGoodsJingfenQueryRequest;
import com.jd.open.api.sdk.request.kplunion.UnionOpenOrderRowQueryRequest;
import com.jd.open.api.sdk.request.kplunion.UnionOpenPromotionCommonGetRequest;
import com.jd.open.api.sdk.response.kplunion.UnionOpenCategoryGoodsGetResponse;
import com.jd.open.api.sdk.response.kplunion.UnionOpenGoodsJingfenQueryResponse;
import com.jd.open.api.sdk.response.kplunion.UnionOpenOrderRowQueryResponse;
import com.jd.open.api.sdk.response.kplunion.UnionOpenPromotionCommonGetResponse;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.common.common.code.SystemErrorCode;
import net.lab1024.sa.common.common.domain.PageResult;
import net.lab1024.sa.common.common.domain.ResponseDTO;
import net.lab1024.sa.common.common.util.SmartPageUtil;
import net.lab1024.sa.common.config.JdUnionConfig;

import net.lab1024.sa.common.module.support.jdunion.constant.OrderStatus;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import net.lab1024.sa.common.module.support.jdunion.domain.vo.*;
import net.lab1024.sa.common.module.support.jdunion.domain.form.*;


@Component
@Slf4j
public class JdUnionService {

    @Autowired
    private JdClient jdClient;

    @Autowired
    private JdUnionConfig jdUnionConfig;

    public ResponseDTO<List<GoodsCategoryVO>> getGoodsCategory(Integer grade,Integer parentId){
        UnionOpenCategoryGoodsGetRequest request=new UnionOpenCategoryGoodsGetRequest();
        CategoryReq req=new CategoryReq();
        req.setGrade(grade);
        req.setParentId(parentId);
        request.setReq(req);
        request.setVersion("1.0");
        try {
            UnionOpenCategoryGoodsGetResponse response=jdClient.execute(request);

            List<GoodsCategoryVO>  goodsCategoryVOList= Arrays.stream(response.getGetResult().getData()).map(categoryResp -> {
                GoodsCategoryVO goodsCategoryVO=new GoodsCategoryVO();
                BeanUtils.copyProperties(categoryResp,goodsCategoryVO);
                return goodsCategoryVO;
            }).collect(Collectors.toList());


            return ResponseDTO.ok(goodsCategoryVOList);
        } catch (Exception e) {
            log.error("获取商品分类失败",e);
        }

        return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR,"获取商品分类失败");

    }

    public ResponseDTO<PageResult<GoodsInfoVO>> getGoodsByGroup(GoodsInfoQueryForm goodsInfoQueryForm){

        UnionOpenGoodsJingfenQueryRequest request=new UnionOpenGoodsJingfenQueryRequest();
        JFGoodsReq goodsReq=new JFGoodsReq();
        goodsReq.setEliteId(goodsInfoQueryForm.getChannelNumber());
        if(goodsInfoQueryForm.getGroupNumber()!=null){
            goodsReq.setGroupId(goodsInfoQueryForm.getGroupNumber().longValue());
        }
        goodsReq.setOwnerUnionId(Long.parseLong(jdUnionConfig.getOwnerUnionId()));
        goodsReq.setSortName("commissionShare");
        goodsReq.setSort("desc");
        goodsReq.setPageIndex(goodsInfoQueryForm.getPageNum());
        goodsReq.setPageSize(goodsInfoQueryForm.getPageSize());
        request.setGoodsReq(goodsReq);
        request.setVersion("1.0");
        try {
            UnionOpenGoodsJingfenQueryResponse response=jdClient.execute(request);

            if(response.getQueryResult().getCode()==200) {


                List<GoodsInfoVO> goodsInfoVOList = Arrays.stream(response.getQueryResult().getData()).map(jFGoodsResp -> {
                    GoodsInfoVO goodsInfoVO = new GoodsInfoVO();
                    goodsInfoVO.setSkuId(jFGoodsResp.getSkuId());
                    goodsInfoVO.setSkuName(jFGoodsResp.getSkuName());
                    goodsInfoVO.setCid1(jFGoodsResp.getCategoryInfo().getCid1());
                    goodsInfoVO.setCid1Name(jFGoodsResp.getCategoryInfo().getCid1Name());
                    goodsInfoVO.setCid2(jFGoodsResp.getCategoryInfo().getCid2());
                    goodsInfoVO.setCid2Name(jFGoodsResp.getCategoryInfo().getCid2Name());
                    goodsInfoVO.setCid3(jFGoodsResp.getCategoryInfo().getCid3());
                    goodsInfoVO.setCid3Name(jFGoodsResp.getCategoryInfo().getCid3Name());
                    goodsInfoVO.setCommissionShare(jFGoodsResp.getCommissionInfo().getCommissionShare());
                    goodsInfoVO.setPrice(jFGoodsResp.getPriceInfo().getPrice());
                    goodsInfoVO.setComments(jFGoodsResp.getComments());
                    goodsInfoVO.setGoodCommentsShare(jFGoodsResp.getGoodCommentsShare());
                    goodsInfoVO.setOwner(jFGoodsResp.getOwner());
                    goodsInfoVO.setMaterialUrl(jFGoodsResp.getMaterialUrl());


                    goodsInfoVO.setImgUrls(Arrays.stream(jFGoodsResp.getImageInfo().getImageList()).map(urlInfo -> urlInfo.getUrl()).toArray(String[]::new));

                    return goodsInfoVO;
                }).collect(Collectors.toList());

                Page page = SmartPageUtil.convert2PageQuery(goodsInfoQueryForm);
                page.setTotal(response.getQueryResult().getTotalCount());


                PageResult<GoodsInfoVO> pageResult = SmartPageUtil.convert2PageResult(page, goodsInfoVOList);


                return ResponseDTO.ok(pageResult);

            }


        } catch (Exception e) {
            log.error("获取商品失败",e);
        }


        return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR,"获取商品失败");

    }


    public ResponseDTO<String> getPromoteUrl(String materialUrl){

        UnionOpenPromotionCommonGetRequest request=new UnionOpenPromotionCommonGetRequest();
        PromotionCodeReq promotionCodeReq=new PromotionCodeReq();
        promotionCodeReq.setMaterialId(materialUrl);
        promotionCodeReq.setSiteId(jdUnionConfig.getSiteId());
        request.setPromotionCodeReq(promotionCodeReq);
        request.setVersion("1.0");
        try {
            UnionOpenPromotionCommonGetResponse response=jdClient.execute(request);
            return ResponseDTO.ok(response.getGetResult().getData().getClickURL());
        } catch (Exception e) {
            log.error("获取商品推广链接失败",e);
        }
        return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR,"获取商品推广链接失败");
    }


    public ResponseDTO<OrderInfoVO> getOrderInfo(Long orderId){
        UnionOpenOrderRowQueryRequest request=new UnionOpenOrderRowQueryRequest();
        OrderRowReq orderReq=new OrderRowReq();
        orderReq.setOrderId(orderId);

        request.setOrderReq(orderReq);
        request.setVersion("1.0");
        try {
            UnionOpenOrderRowQueryResponse response=jdClient.execute(request);

            if(response.getQueryResult().getCode()==200){

                OrderInfoVO orderInfoVO=new OrderInfoVO();

                orderInfoVO.setEstimateCosPrice(new AtomicDouble());
                orderInfoVO.setActualCosPrice(new AtomicDouble());
                orderInfoVO.setEstimateFee(new AtomicDouble());
                orderInfoVO.setActualFee(new AtomicDouble());
                List<OrderItemVO> orderItemVOList=Arrays.stream(response.getQueryResult().getData()).map(orderRowQueryResult->{

                    OrderItemVO orderItemVO=new OrderItemVO();

                    BeanUtils.copyProperties(orderRowQueryResult,orderItemVO);

                    BeanUtils.copyProperties(orderRowQueryResult,orderInfoVO);

                    orderInfoVO.getEstimateCosPrice().addAndGet(orderRowQueryResult.getEstimateCosPrice());
                    orderInfoVO.getEstimateFee().addAndGet(orderRowQueryResult.getEstimateFee());
                    orderInfoVO.getActualCosPrice().addAndGet(orderRowQueryResult.getActualCosPrice());
                    orderInfoVO.getActualFee().addAndGet(orderRowQueryResult.getActualFee());


                    if(orderRowQueryResult.getValidCode().equals(17)){

                        orderInfoVO.setOrderStatus(OrderStatus.COMPLETED);

                    }else{

                        orderInfoVO.setOrderStatus(OrderStatus.INVALID);
                    }

                    return orderItemVO;

                }).collect(Collectors.toList());

                orderInfoVO.setOrderItemVOList(orderItemVOList);

                return ResponseDTO.ok(orderInfoVO);

            }

        } catch (Exception e) {

            log.error("获取订单失败",e);

        }

        return ResponseDTO.error(SystemErrorCode.SYSTEM_ERROR,"获取订单失败");
    }


}
